package com.kiliter.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.kiliter.config.RedisService;
import com.kiliter.exception.KiliterException;
import com.kiliter.service.ApiTokenService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author YUKI
 * @ClassName zhangjl
 * @date 2021/6/7 10:45
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class ApiTokenServiceImpl implements ApiTokenService {

    private final RedisService redisService;

    @Override
    public String createToken() {
        String idStr = IdWorker.getIdStr();
        String key = "API:" + idStr;
        redisService.set(key, key, 60 * 60);
        return key;
    }

    @Override
    public void checkToken(HttpServletRequest res) {
        String apitoken = res.getHeader("APITOKEN");
        if (StringUtils.isBlank(apitoken)) {
            String apitoken1 = res.getParameter("APITOKEN");
            if (StringUtils.isBlank(apitoken1)) {
                throw new KiliterException(200, "幂等token未传");
            }
        }
        if (!redisService.hasKey(apitoken)) {
            throw new KiliterException(200, "请勿重复提交");
        }

        Boolean key = redisService.del(apitoken);
        if (!key) {
            throw new KiliterException(201, "请勿重复提交");
        }
    }
}
